package jp.sourceforge.akjrcp.videotools.dvdtoxvid;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

public class CheckToRadio implements SelectionListener{
	private List buttons=new ArrayList();
	
	public Button createButton(Composite parent,int layout){
		Button button=new Button(parent,SWT.CHECK|layout);
		button.addSelectionListener(this);//check to radio
		this.addButton(button);
		return button;
	}
	
	public Button getSelection(){
		int index=0;
		for(int i=0;i<buttons.size();i++){
			Button bt=(Button)buttons.get(index);
			if(bt.getSelection()){
				return bt;
			}
		}
		return null;
	}
	public void select(Button target){
		
		int index=0;
		for(int i=0;i<buttons.size();i++){
			if(target==buttons.get(i)){
				index=i;
				break;
			}
	
		
		}
	
		Button bt=(Button)buttons.get(index);
		
		
		bt.setSelection(true);
		for(int i=0;i<buttons.size();i++){
			if(bt!=buttons.get(i)){
				((Button)buttons.get(i)).setSelection(false);
			}
		}
		/*
		if(bt.getSelection()){
			//unselect all
			for(int i=0;i<buttons.size();i++){
				if(bt!=buttons.get(i)){
					((Button)buttons.get(i)).setSelection(false);
				}
			}
		}else{
		// i don't know reason why
			boolean unselectAll=true;
			for(int i=0;i<buttons.size();i++){
				Button bt2=(Button)buttons.get(i);
				if(bt2.getSelection()){
					unselectAll=false;
					break;
				}
			}
			if(unselectAll){
				bt.setSelection(true);//keep at leaset 1 selection
			}
		}*/
	}
	public void addButton(Button bt){
		if(buttons.size()==0){
			bt.setSelection(true);//select first one
		}
		buttons.add(bt);
		
	}
	public void widgetDefaultSelected(SelectionEvent e) {
		
	}
	public void widgetSelected(SelectionEvent e) {
		select((Button) e.getSource());
	}
}